package com.hunttown.mes.manage.service;

import com.hunttown.mes.common.utils.DateConvertUtils;
import com.hunttown.mes.common.utils.FastJsonUtils;
import com.hunttown.mes.common.utils.GeneralUtils;
import com.hunttown.mes.common.utils.StringUtils;
import com.hunttown.mes.rpc.domain.TransportTableChineseEnglishDTO;
import com.hunttown.mes.rpc.domain.TransportTableChineseEnglishDetailDTO;
import com.hunttown.mes.rpc.domain.enums.log.OperateTypeEnum;
import com.hunttown.mes.rpc.domain.query.TransportTableChineseEnglishDetailDTOQuery;
import com.hunttown.common.domain.Page;
import com.hunttown.mes.rpc.api.TransportOperateLogRpcService;
import com.hunttown.mes.rpc.domain.TransportOperateLogDTO;
import com.hunttown.mes.rpc.domain.query.TransportOperateLogDTOQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;

import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * created by wangjunfu on 2019-05-19 01:51:47
 */
@Service
public class TransportOperateLogManageService {

    private final static Logger logger = LoggerFactory.getLogger(TransportOperateLogManageService.class);

    private final TransportOperateLogRpcService rpcService;
    private final TransportTableChineseEnglishManageService englishService;
    private final TransportTableChineseEnglishDetailManageService englishDetailService;
    private final AnalysisManageManageService manageService;

    @Autowired
    public TransportOperateLogManageService(TransportOperateLogRpcService rpcService, TransportTableChineseEnglishManageService englishService, TransportTableChineseEnglishDetailManageService englishDetailService, AnalysisManageManageService manageService) {
        this.rpcService = rpcService;
        this.englishService = englishService;
        this.englishDetailService = englishDetailService;
        this.manageService = manageService;
    }

    // 新增
    public TransportOperateLogDTO insert(TransportOperateLogDTO objDTO) {
        return rpcService.insert(objDTO);
    }

    // 新增
    // modelType：1管理员 2司机 3会员 4长期订车
    // opType：1创建C 2更新U 3读取R 4删除D
    public void insertSimple(Integer modelType, Integer tableid, Integer recordid, Integer opType,
                             String title, String content, Integer opPeople, String ip, String browser) {
        try {
            TransportOperateLogDTO dto = new TransportOperateLogDTO();
            dto.setModelType(modelType);
            dto.setTableId(tableid);
            dto.setRecordId(recordid);
            dto.setOpType(opType);
            dto.setOpTitle(title);
            dto.setOpContent(content);
            dto.setOpPeople(opPeople);
            dto.setOpTime(new Date());
            dto.setOpIp(ip);
            dto.setOpBrowser(browser);
            insert(dto);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    // 通过ID修改
    public Boolean updateInfoById(TransportOperateLogDTO objDTO) {
        return rpcService.updateInfoById(objDTO);
    }

    // 通过Query修改
    public Boolean updateInfoByQuery(TransportOperateLogDTOQuery objDTOQuery) {
        return rpcService.updateInfoByQuery(objDTOQuery);
    }

    // 通过ID获取
    public TransportOperateLogDTO getById(Integer id) {
        if (id <= 0) {
            return null;
        }
        return rpcService.selectById(id);
    }

    // 通过Query获取
    public TransportOperateLogDTO getByQuery(TransportOperateLogDTOQuery objDTOQuery) {
        return rpcService.selectObjByQuery(objDTOQuery);
    }

    // 获取分页列表
    public Page<TransportOperateLogDTO> getForPage(TransportOperateLogDTOQuery objDTOQuery) {
        return rpcService.getListForPage(objDTOQuery);
    }

    //region 数据查看

    /**
     * 组装实体信息为前台可展示的格式
     * 可做定制化的配置
     * 存放位置：各业务的Service中
     *
     * @param model     Sevelet Model
     * @param tableName 数据库表名
     * @param obj       对象
     * @return
     */
    public Model assembleObjInfo(Model model, String tableName, TransportOperateLogDTO obj) {

        // 结果集返回一个map
        LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();

        // 显示标题
        String showTitle = "详情";

        // 获取数据库中英文对照表主表信息
        TransportTableChineseEnglishDTO englishDTO = englishService.getByTableName(tableName);

        if (obj == null || englishDTO == null) {
            map.put("没有查询到数据！", "");
        } else {
            Map<String, Object> origin_map = GeneralUtils.ergodicModel(FastJsonUtils.toJSONString(obj), TransportOperateLogDTO.class);

            if (origin_map != null) {
                // 根据表ID（tableId）获取表字段信息
                TransportTableChineseEnglishDetailDTOQuery query = new TransportTableChineseEnglishDetailDTOQuery();
                query.setTableId(englishDTO.getId());
                query.setDeleteFlag(0);
                query.setPageSize(1000);
                Page<TransportTableChineseEnglishDetailDTO> detailPage = englishDetailService.getForPage(query);

                if (detailPage != null && detailPage.getItems().size() > 0) {
                    Object value;
                    String newfield;
                    for (TransportTableChineseEnglishDetailDTO item : detailPage.getItems()) {
                        if (item.getFrontShow() == 1) {
                            newfield = GeneralUtils.standardFields(item.getFieldName());
                            value = origin_map.get(newfield);
                            if (item.getFieldType().toUpperCase().equals("TIMESTAMP")) {
                                map.put(item.getFieldNameCn(), DateConvertUtils.cstToShortStrDate(value.toString()));
                            } else {

                                if (value == null || StringUtils.isBlank(value.toString())) {
                                    map.put(item.getFieldNameCn(), "--");
                                    continue;
                                }

                                //region 开始个性化设置
                                if (newfield.equals("tableId")) {
                                    TransportTableChineseEnglishDTO dto = englishService.getById(Integer.valueOf(value.toString()));
                                    if (dto != null) {
                                        value = dto.getTableNameCn();
                                    }
                                }
                                if (newfield.equals("opType")) {
                                    value = OperateTypeEnum.getEnumByKey(Integer.valueOf(value.toString()));
                                }
                                if (newfield.equals("opContent")) { //内容太多，单独显示
                                    value = "--";
                                }
                                if (newfield.equals("opPeople")) {
                                    value = manageService.getNickNameFromCache(Integer.valueOf(value.toString()));
                                    showTitle = value.toString();
                                }
                                if (newfield.equals("stopFlag")) { //启停用状态
                                    value = value.equals(0) ? "启用" : "停用";
                                }
                                //endregion

                                map.put(item.getFieldNameCn(), value.toString());
                            }
                        }
                    }
                }
            }
        }

        model.addAttribute("showTitle", showTitle);
        model.addAttribute("showResult", map);

        return model;
    }

    //endregion
}